package com.sojson.project.pay.controller.ali.param.verify;

import java.util.HashMap;
import java.util.Map;

import com.alipay.api.internal.util.AlipaySignature;
import com.sojson.util.StringUtil;
import com.sojson.util.SystemParamBaseUtil;
import com.sojson.util.json.JsonUtil;
import com.sojson.util.pay.ali.bean.AliResponse;
import com.sojson.util.pay.ali.constant.AliConstant;
import com.sojson.util.servlet.ServletUtil;

/**
 * 支付宝支付参数验证
 *
 * @author liu
 * @date 2021-03-16
 */
public class PayAliParamVerify {

    /**
     * 支付回调
     *
     * @return
     * @throws Exception
     */
    public static AliResponse payNotify() throws Exception {
        Map<String, String> hashMap = null;
        String body = ServletUtil.getParamBody();
        if (StringUtil.isBlankString(body)) {
            hashMap = ServletUtil.getParameterMapString();
            if (StringUtil.isBlankObject(hashMap)) {
                return null;
            }
        } else {
            hashMap = new HashMap<>();
            body = StringUtil.decode(body);
            String[] split = body.split("&");
            for (String string : split) {
                int indexOf = string.indexOf("=");
                hashMap.put(string.substring(0, indexOf), string.substring(indexOf + 1));
            }
        }

        AliResponse jsonToObject = JsonUtil.jsonToObject(JsonUtil.objectToJson(hashMap), AliResponse.class);

        boolean rsaCertCheckV1 = AlipaySignature.rsaCheckV1(hashMap,
            SystemParamBaseUtil.getStr(AliConstant.CA_CERT_CACHE_KEY_ALIPAY_CERT_PUBLIC), jsonToObject.getCharset(),
            jsonToObject.getSignType());
        if (!rsaCertCheckV1) {
            return null;
        }

        return jsonToObject;
    }

}